/**
 * Copyright 2009 - Morten Udnæs
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.javabatch.petstore.records;

import java.util.List;

import com.javabatch.fileio.Field;
import com.javabatch.fileio.FieldError;
import com.javabatch.fileio.FieldType;
import com.javabatch.fileio.FileBuffer;

public enum PriceRecord implements Record {

	ANIMAL_ID (new Field(0,0,38, FieldType.TEXT)),
	ANIMAL_NAME (new Field(1,38,60, FieldType.TEXT)),
	ANIMAL_PRICE (new Field(2,98,16, FieldType.NUMBER));
	
	private Field field;
	
	PriceRecord(Field theField) {
		this.field = theField;
	}

	  public byte[] readRaw(FileBuffer inputData, List<FieldError> errors) {
	        return field.parseField(inputData, this.toString(), errors);
	    }

	    public String read(FileBuffer inputData, List<FieldError> errors) {
	        return new String(readRaw(inputData, errors));
	    }

	    public void writeRaw(FileBuffer outputData, byte[] fieldValue) {
	        Field.addFieldToRecord(fieldValue, this.field, outputData);
	    }

	    public void write(FileBuffer outputData, String fieldValue) {
	        Field.addFieldToRecord(fieldValue, this.field, outputData);
	    }

	  
	    public static int getRecordLength() {
	        int calculatedLength = 0;
	        for (PriceRecord record : PriceRecord.values()) {
	            calculatedLength += record.field.getLength();
	        }
	        return calculatedLength;
	    }

	    public static int getLengthAndValidateRecord() {
	        int i = 0;
	        Field[] fields = new Field[PriceRecord.values().length];

	        for (PriceRecord record : PriceRecord.values()) {
	            fields[i++] = record.field;
	        }

	        // Validate that there are no holes between field definitions
	        int lastFieldEndPos = fields[fields.length - 1].getStartPos()
	                + fields[fields.length - 1].getLength();
	        if (getRecordLength() != lastFieldEndPos) {
	            throw new IllegalArgumentException("Sum of records length: "
	                    + getRecordLength()
	                    + "  doesn't match last field startpos + length: "
	                    + lastFieldEndPos);
	        }
	        return getRecordLength();

	    }
	}
